﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace CH.FourBoards.LagerWalti.FrontEnd.View.Util
{
	internal class ContentRenderer
	{
		private const string DateFormat = "dd.MM.yyyy";
		private const string DateTimeFormat = "dd.MM.yy HH:mm:ss";
		public string ToDateOnly(DateTime value)
		{
			return value.ToString(DateFormat);
		}

		public string ToDateOnly(DateTime? value)
		{
			return value.HasValue ? ToDateOnly(value.Value) : string.Empty;
		}

		public string ToDateTime(DateTime value)
		{
			return value.ToString(DateTimeFormat);
		}

		public string ToDateTime(DateTime? value)
		{
			return value.HasValue ? ToDateTime(value.Value) : string.Empty;
		}

		public string Format(TimeSpan value)
		{
			return value.ToString("c");
		}

		public string ToSeconds(TimeSpan value)
		{
			return string.Format("{0} sec", value.TotalSeconds);
		}

		public string ToSeconds(TimeSpan value, int digits)
		{
			var digitString = new string('0', digits);
			var format = "{0:0." + digitString + "} sec";
			return string.Format(format, value.TotalSeconds);
		}

		public string Format(TimeSpan? value)
		{
			return value.HasValue ? Format(value.Value) : string.Empty;
		}

		public string Format(Exception ex)
		{
			var ret = ex.Message;
			while (ex.InnerException != null) {
				ex = ex.InnerException;
				ret += "<br>" + ReplaceLineFeeds(ex.Message);
			}
			return ret;
		}

		private string ReplaceLineFeeds(string value)
		{
			return value.Replace("\n", "<br>");
		}

		public DateTime? ParseDateTime(string value)
		{
			DateTime ret;
			if (DateTime.TryParseExact(value, DateTimeFormat, null, DateTimeStyles.None, out ret)) {
				return ret;
			}
			return null;
		}

		public TimeSpan? ParseTimeSpan(string value)
		{
			TimeSpan ret;
			if (TimeSpan.TryParse(value, out ret)) {
				return ret;
			}
			return null;
		}

        internal string CreateAttributeString(IEnumerable<KeyValuePair<string, string>> attributes)
        {
            var items = attributes.Select(attribute => string.Format("{0}=\"{1}\"", attribute.Key, attribute.Value));
            return string.Join(" ", items);
        }
	}
}